import upload from "./upload.js";

let updateDialog, form;
fetch("country-update.html").then(r => r.text()).then(text => {
    updateDialog = $(text);
    console.debug(updateDialog);
    $("body").append(updateDialog);

    form = updateDialog[0].querySelector("form");

    let btn = updateDialog[0].querySelector("._save");

    console.debug(updateDialog, form, btn);

    btn.onclick = function () {
        let params = new URLSearchParams(new FormData(form));
        console.debug(params.toString());
        fetch("country-update.let", {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'include', // include, *same-origin, omit
            headers: {
                // 'Content-Type': 'application/json'
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            // body: JSON.stringify(data) // body data type must match "Content-Type" header
            body: params
        }).then(r => r.json()).then((data) => {
            console.debug(data);
            if (data.ok) {
                updateDialog.modal("hide");
                form.reset();//重置
                window.postMessage("loadData");//发送消息
            } else {
                alert(data.msg);
            }
        }).catch(e => {
            console.error(e);
        });
    }
});
export default function (item) {
    updateDialog.modal("show");
    // form.countryCode.value = item.countryCode;
    // form["countryCode"].value = item["countryCode"];
    for (let name in item) {
        form[name].value = item[name];
    }

    upload(updateDialog.find("._upload")[0], function (data) {
        form.countryUri.value = data.uri;
    }, "down.let?file=" + item.countryUri);

}
